package com.cmo.common.config;

import java.sql.Connection;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.cmo.common.FrontRoutes;
import com.cmo.common.model._MappingKit;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.ext.handler.ContextPathHandler;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.json.MixedJsonFactory;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.template.Engine;


public class BaseConfig extends JFinalConfig {

	private static Prop p=loadConfig();
	
	private WallFilter wallfilter;
	@Override
	public void configConstant(Constants me) {
		//me.setDevMode(p.getBoolean("devMode", true));
		me.setDevMode(p.getBoolean("devMode", false));
		me.setJsonFactory(MixedJsonFactory.me());
		//me.setViewType(ViewType.JSP);
	}

	@Override
	public void configRoute(Routes me) {
		me.add(new FrontRoutes());
		
	}
	
	
	@Override
	public void configEngine(Engine me) {
		
	}


	public static DruidPlugin getDruidPlugin() {
		return new DruidPlugin(p.get("jdbcUrl"), p.get("user"), p.get("password").trim());
	}
	

	@Override
	public void configPlugin(Plugins me) {
		DruidPlugin druidPlugin = getDruidPlugin();
	    wallfilter = new WallFilter();              // 加强数据库安全
	    wallfilter.setDbType("mysql");
	    druidPlugin.addFilter(wallfilter);
	    druidPlugin.addFilter(new StatFilter());    // 添加 StatFilter 才会有统计数据
	    me.add(druidPlugin);
	    
	    ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
	    arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
	    
	    _MappingKit.mapping(arp);
	    me.add(arp);
	    if (p.getBoolean("devMode", true)) {
            arp.setShowSql(true);
        }
        
	    me.add(new EhCachePlugin());//缓存
	    //me.add(new Cron4jPlugin(p));//定时器
	}


	@Override
	public void configInterceptor(Interceptors me) {
		me.add(new SessionInViewInterceptor());
		
	}
	

	@Override
	public void afterJFinalStart() {
		// 让 druid 允许在 sql 中使用 union
		wallfilter.getConfig().setSelectUnionCheck(false);
		super.afterJFinalStart();
		System.out.println("afterJFinalStart。。。");
	}

	public static void main(String[] args) {
		//启动项目
		JFinal.start("src/main/webapp", 82, "/", 5);
	}

	private static Prop loadConfig(){
		return PropKit.use("jfinal_club_config_dev.txt");
	}

	@Override
	public void configHandler(Handlers me) {
		// TODO Auto-generated method stub
		me.add(new ContextPathHandler("basepath"));
	}
}
